﻿//----------------------------------------------------------------------//
//                                                                      //
//                    页面控件类型、为空验证、XML操作                   //
//                                                                      //
//                  需要外面调用页面引用 Common.js文件                  //
//                                                                      //
//----------------------------------------------------------------------//

/// <summary>
/// 公用函数类
/// </summary>
function Func()
{
    throw new Error("公用函数类(Func)是静态类, 不能创建对象!");
}

/// <summary>
/// 判断对象是否有效
/// </summary>
/// <param name="value">判断的对象</param>
/// <returns>是否有效</returns>
function Func.isNull(value)
{
    return (value == null || typeof(value) == "undefined")
}

/// <summary>
/// 计算控件绝对位置
/// </summary>
/// <param name="obj">控件</param>
/// <returns>绝对位置</returns>
function Func.getAbsPos(obj)
{
    var pt = new Object();
    pt.top = obj.offsetTop;
    pt.left = obj.offsetLeft;
    while (obj = obj.offsetParent)
    {
        pt.top += obj.offsetTop;
        pt.left += obj.offsetLeft;
    }
    return pt;
}

/// <summary>
/// 对数字型的串加上逗号
/// </summary>
/// <param name="value">数字</param>
/// <returns>加上逗号后数字</returns>
function Func.addCommas(value)
{
    var objRegExp = new RegExp("([-,+]?[0-9]+)([0-9]{3})");
    while(objRegExp.test(value)) 
    {
        value = value.replace(objRegExp, "$1,$2");
    }
    return value;
}

/// <summary>
/// 移除数字中的逗号
/// </summary>
/// <param name="value">数字</param>
/// <returns>移除逗号后数字</returns>
function Func.removeCommas(value)
{
    return value.replace(/,/g, "");
}

/// <summary>
/// 初始化控件容器中所有控件事件
/// </summary>
/// <param name="container">控件容器</param>
function Func.initDataTypeEvent(container)
{
    if (!container)
    {
        // 若容器为空, 设置默认容器为整个页面文档
        container = document.body;
    }

    initChildNodes(container.childNodes);

    /// <summary>
    /// 递归附加控件容器中子控件事件
    /// </summary>
    /// <param name="controls">控件集合</param>
    function initChildNodes(controls)
    {
        for(var i=0; i<controls.length; i++)
        {
            Func.attachEvent(controls[i]);
            initChildNodes(controls[i].childNodes);
        }
    }
}

/// <summary>
/// 附加控件事件
/// </summary>
/// <param name="control">控件对象</param>
function Func.attachEvent(control)
{
    if (control.tagName == "INPUT" && control.getAttribute("datatype"))
    {
        control.setAttribute("datatype", control.getAttribute("datatype").toLowerCase());
    }
    switch (control.type)
    {
        case "password":
        case "text":
            attachKeydownEvent(control);
            // 日期选择框, 不附加事件
            if (control.datatype != "date")
            {
                attachFocusEvent(control);
                attachBlurEvent(control);
                attachKeypressEvent(control);
                attachKeyupEvent(control);
            }

            // 如果是数值型框, 把值右边对齐, 根据属性, 是否加逗号
            if (isNumType(control.datatype))
            {   
                control.style.textAlign = "right";
                if (control.getAttribute("HasComma") && control.getAttribute("HasComma").toLowerCase() == "true")
                {
                    control.value = Func.addCommas(control.value.trim());
                }
            }
            break;
        case "checkbox":
            attachFocusEvent(control);
            attachBlurEvent(control);
            attachKeydownEvent(control);
            break;
        case "textarea":
            attachFocusEvent(control);
            attachBlurEvent(control);
            break;
        case "select-one":
        case "select-multiple":
            attachFocusEvent(control);
            attachBlurEvent(control);
            attachKeydownEvent(control);
            break;
        default:
            break;
    };

    function attachFocusEvent(control)
    {
        control.focusEventPre = control.onfocus;
        control.onfocus = focusEvent;
    }

    function attachBlurEvent(control)
    {
        control.blurEventPre = control.onblur;
        control.onblur = blurEvent;
    }
    
    function attachKeypressEvent(control)
    {
        control.keypressEventPre = control.onkeypress;
        control.onkeypress = keypressEvent;
    }

    function attachKeydownEvent(control)
    {
        control.keydownEventPre = control.onkeydown;
        control.onkeydown = keydownEvent;
    }

    function attachKeyupEvent(control)
    {
        control.keyupEventPre = control.onkeyup;
        control.onkeyup = keyupEvent;
    }

    function focusEvent()
    {
        var obj = event.srcElement;
        
        showInfo(obj, "info");
        if (isNumType(obj.datatype))
        {
            obj.style.textAlign = "left";
            if (obj.getAttribute("HasComma") && obj.getAttribute("HasComma").toLowerCase() == "true")
            {
            obj.value = Func.removeCommas(obj.value.trim());
            }

            obj.focus();
            obj.select();
        }

        if (obj.focusEventPre)
        {
            obj.focusEventPre();
        }
    }

    function blurEvent()
    {
        var obj = event.srcElement;
        
        getEventPopup().hide();
        if (isNumType(obj.datatype))
        {
            obj.style.textAlign = "right";
            if (obj.getAttribute("HasComma") && obj.getAttribute("HasComma").toLowerCase() == "true")
            {
                obj.value = Func.addCommas(obj.value.trim());
            }
        }

        if (obj.blurEventPre)
        {
            obj.blurEventPre();
        }
    }

    function keypressEvent()
    {
        var obj = event.srcElement;
        var keyCode = event.keyCode;
        
        var dt = obj.datatype;
        
        //整数类型, 不带小数点
        if (dt == "int" || dt == "num0")
        {
            if ((keyCode >= 48 && keyCode <= 57) || keyCode == 45)
            {
                return true
            }
            else
            {
                return false;
            }
        }
        
        //浮点数类型, 可以带小数点
        else if (dt == "num2" || dt == "num4")
        {
            if ((keyCode >= 48 && keyCode <= 57) || keyCode == 46 || keyCode == 45)
            {
                return true
            }
            else
            {
                return false;
            }
        }

        if (obj.keypressEventPre)
        {
            return obj.keypressEventPre();
        }
        
        return true;
    }

    function keydownEvent()
    {
        var obj = event.srcElement;
        var keycode = event.keyCode;

        if (event.keyCode == 13)
        {
            if (obj.getAttribute("AutoTab") && obj.getAttribute("AutoTab").toLowerCase() == "true")
            {
                event.keyCode = 9;
            }

            // qianwt
            // 2007-08-26
            // 加入回车键执行脚本
            if (obj.getAttribute("EnterScript"))
            {
                eval(obj.getAttribute("EnterScript"));
            }
        }

        if (obj.keydownEventPre)
        {
            // qianwt
            // 2007-08-30
            // 如果父项事件模型有返回值, 就直接返回去            
            return obj.keydownEventPre();
        }
    }

    function keyupEvent(evnt)
    {
        var obj = event.srcElement;

        showInfo(obj, "error");

        if (obj.keyupEventPre)
        {
            obj.keyupEventPre();
        }
    }

    var eventPopup;

    function getEventPopup()
    {
        if (!eventPopup)
        {
            eventPopup = window.createPopup();
            eventPopup.document.body.onmousedown = function() { eventPopup.hide(); };
        }
        return eventPopup;
    }

    /// <summary>
    /// 控件类型是否货币类型
    /// </summary>
    /// <param name="datatype">控件类型</param>
    /// <returns>是否货币类型</returns>
    function isNumType(datatype)
    {
        return (datatype == "int" || datatype == "num0" || datatype == "num2" || datatype == "num4");
    }

    /// <summary>
    /// 根据控件类型, 控件值得到错误信息
    /// </summary>
    /// <param name="obj">控件</param>
    /// <returns>错误信息</returns>
    function getErrorMsg(obj)
    {
        var msg = "";
        switch(obj.datatype)
        {
            case "int":
                if(!(obj.value.trim().isInt()))
                    msg = "您只能输入整数, 且长度不超过10位!";
                break;
            case "num0":
                if(!(obj.value.trim().isNum0()))
                    msg = "您不能输入带有小数点的数, 且长度不超过16位!";
                break;
            case "num2":
                if(!(obj.value.trim().isNum2()))
                    msg = "您只能输入带两位小数点的小数, 且长度不超过16位!";
                break;
            case "num4":
                if(!(obj.value.trim().isNum4()))
                    msg = "您只能输入带四位小数点的小数, 且长度不超过16位!";
                break;
        }
        return msg;
    }

    /// <summary>
    /// 显示自定义提醒或者警告
    /// </summary>
    /// <param name="obj">控件</param>
    /// <param name="type">显示类型</param>
    function showInfo(obj, type)
    {
        var infobox = document.getElementById("InfoBoxDiv");
        if (!infobox)
        {
            infobox = document.createElement("DIV");
            document.body.insertBefore(infobox, document.body.firstChild);
            infobox.outerHTML = "<div id=\"InfoBoxDiv\" style=\"position:absolute; top:0px; left:0px; FONT-SIZE: 12px; color:#333333; padding: 8px 8px 8px 8px; LINE-HEIGHT: 18px; BORDER: #E3E3E3 solid 1px; BACKGROUND: #FFFFEE; WIDTH: 240px; DISPLAY: none\"></div>";
            infobox = document.getElementById("InfoBoxDiv");
        }

        //显示内容
        if(type == "info")
        {
            if (obj.style.backgroundColor == "yellow")
            {
                showInfo(obj, "error");
                return;
            }

            if (Func.isNull(obj.getAttribute("Tipmsg")))
                return;

            infobox.style.display = "block";
            infobox.innerHTML = "<img src=\"" + ApplicationPath + '/App_Themes' + ThemePath + "/images/standard_msg_warning.gif\"> " + obj.getAttribute("Tipmsg");

            var left;
            if (Func.getAbsPos(obj).left + obj.offsetWidth + infobox.clientWidth > document.body.clientWidth)
            {
                left = - infobox.clientWidth - 2;
            }
            else
            {
                left = obj.offsetWidth;
            }

            getEventPopup().document.body.innerHTML = infobox.outerHTML;
            getEventPopup().show(left, 0, infobox.offsetWidth, infobox.offsetHeight, obj);
            
            infobox.style.display = "none";
        }
        else if(type == "error")
        {
            var msg = getErrorMsg(obj);
            if (msg != "")
            {
                infobox.style.display = "block";
                infobox.innerHTML    = "<img src=\"" + ApplicationPath + '/App_Themes' + ThemePath + "/images/standard_msg_error.gif\"> " + msg;
                obj.style.backgroundColor = "yellow"

                var left;
                if (Func.getAbsPos(obj).left + obj.offsetWidth + infobox.clientWidth > document.body.clientWidth)
                {
                    left = - infobox.clientWidth - 2;
                }
                else
                {
                    left = obj.offsetWidth;
                }
            
                getEventPopup().document.body.innerHTML = infobox.outerHTML;
                getEventPopup().show(left, 0, infobox.offsetWidth, infobox.offsetHeight, obj);

                infobox.style.display = "none";
            }
            else if (obj.style.backgroundColor == "yellow")
            {
                obj.style.backgroundColor = "white";
                showInfo(obj, "info");
            }
        }
    }
}

/// <summary>
/// 检查容器中控件数据是否有效
/// </summary>
/// <param name="container">控件容器</param>
function Func.checkData(container)
{
    if (!container)
    {
        // 若容器为空, 设置默认容器为整个页面文档
        container = document.body;
    }

    // 执行递归检查之前方法
    if (window.checkDataBefore && !window.checkDataBefore())
        return false;

    // 递归检查数据
    if (!initChildNodes(container.childNodes))
        return false;

    // 执行递归检查之后方法
    if (window.checkDataAfter && !window.checkDataAfter())
        return false;

    return true;

    /// <summary>
    /// 递归检查控件数据是否有效
    /// </summary>
    /// <param name="controls">控件集合</param>
    function initChildNodes(controls)
    {
        for(var i=0; i<controls.length; i++)
        {
            if (!Func.checkControlData(controls[i]))
                return false;

            if (!initChildNodes(controls[i].childNodes))
                return false;
        }

        return true;
    }
}

/// <summary>
/// 检查控件数据是否有效
/// </summary>
/// <param name="control">控件对象</param>
function Func.checkControlData(control)
{
    switch (control.type)
    {
        case "checkbox":
        case "password":
        case "text":
        case "textarea":
            // 判断文本框是否允许空值
            if (control.getAttribute("AllowEmpty") && control.getAttribute("AllowEmpty").toLowerCase() == "false" && control.value.trim() == "")
            {
                MessageBox.show("info", Func.isNull(control.getAttribute("EmptyErrorMessage")) ? "此项值不能为空, 请输入!" : control.getAttribute("EmptyErrorMessage"), "", function() { setFocus(control) });
                return false;
            }

            // 判断文本框的值类型是否正确
            var datatype = control.getAttribute("datatype");
            if (datatype)
            {
                var methodName = datatype = "is" + datatype.substring(0, 1).toUpperCase() + datatype.substring(1).toLowerCase();
                if (!eval("Func.removeCommas(control.value.trim())." + methodName + "()"))
                {
                    MessageBox.show("info", Func.isNull(control.getAttribute("TypeErrorMessage")) ? "此项值类型错误, 请重新输入!" : control.getAttribute("TypeErrorMessage"), "", function() { setFocus(control) });
                    return false;
                }
            }
            
            // 当文本框的值不为空的时候, 检查是否符合正则表达式
            if (control.value != "" && control.getAttribute("RegExp") && control.value.match(new RegExp(control.getAttribute("RegExp"))) == null)
            {
                MessageBox.show("info", Func.isNull(control.getAttribute("RegErrorMessage")) ? "此项值输入错误, 请输入!" : control.getAttribute("RegErrorMessage"), "", function() { setFocus(control) });
                return false;
            }

            // 检查执行方法
            var execfunc = control.getAttribute("execfunc");
            if (execfunc)
            {
                var func = window[execfunc];
                if (func && typeof(func) == "function")
                {
                    if (func() == false)
                    {
                        return false;
                    }
                }
            }

            break;
        case "select-one":
            // 判断下拉框是否允许空值
            if (control.getAttribute("AllowEmpty") && control.getAttribute("AllowEmpty").toLowerCase() == "false")
            {
                var selectedIndex = control.selectedIndex;
                if (selectedIndex == -1 || control.options[selectedIndex].value == "")
                {
                    MessageBox.show("info", Func.isNull(control.getAttribute("EmptyErrorMessage")) ? "此项值不能为空, 请选择!" : control.getAttribute("EmptyErrorMessage"), "", function() { setFocus(control) });
                    return false;
                }
            }

            // 检查执行方法
            var execfunc = control.getAttribute("execfunc");
            if (execfunc)
            {
                var func = window[execfunc];
                if (func && typeof(func) == "function")
                {
                    if (func() == false)
                    {
                        return false;
                    }
                }
                else
                {
                    throw new Error("没有找到对应 JavaScript 方法: " + execfunc);
                }
            }

            break;
        default:
            break;
    };
    return true;

    /// <summary>
    /// 如果可以获得焦点, 让控件获得焦点
    /// </summary>
    /// <param name="control">控件对象</param>
    function setFocus(control)
    {
        control.focus
        try
        {
            control.focus();
            control.select();
        }
        catch(e)
        {
        }
    }
}

/// <summary>
/// 禁用容器中控件的（text改成只读、checkbox、不让单击、radio, select disabled）
/// </summary>
/// <param name="container">容器</param>
/// <param name="inputclassname">文本框样式表</param>
/// <param name="textareaclassname">多行文本框样式表</param>
function Func.disabledContainer(container, inputclassname, textareaclassname)
{
    if (!container)
    {
        // 若容器为空, 设置默认容器为整个页面文档
        container = document.body;
    }

    disabledChildNodes(container.childNodes, inputclassname, textareaclassname);

    /// <summary>
    /// 递归禁用控件容器中子控件
    /// </summary>
    /// <param name="controls">控件集合</param>
    function disabledChildNodes(controls, childNodesinputclassname, textareaclassname)
    {
        for(var i=0; i<controls.length; i++)
        {
            Func.disabledControl(controls[i], inputclassname, textareaclassname);
            disabledChildNodes(controls[i].childNodes, childNodesinputclassname, textareaclassname);
        }
    }
}

/// <summary>
/// 禁用控件（text改成只读、checkbox、不让单击、radio, select disabled）
/// </summary>
/// <param name="control">控件对象</param>
/// <param name="inputclassname">文本框样式表</param>
/// <param name="textareaclassname">多行文本框样式表</param>
function Func.disabledControl(control, inputclassname, textareaclassname)
{
    switch (control.type)
    {
        case "password":
        case "text":
            control.onblur = null;
            control.onkeypress = null;
            control.onkeydown = null;
            control.onkeyup = null;
            control.onclick = null;
            control.onfocus = null;
            control.readOnly = true;
            control.className = inputclassname;
            break;
        case "textarea":
            control.onblur = null;
            control.onkeypress = null;
            control.onkeydown = null;
            control.onkeyup = null;
            control.onclick = null;
            control.onfocus = null;
            control.readOnly = true;
            control.className = textareaclassname;
            break;
        case "checkbox":
            control.onclick = function(){return false;}
            break;
        case "radio":
            control.disabled = true;
            break;
        case "select-one":
        case "select-multiple":
            control.disabled = true;
            break;
        default:
            break;
    };
}

/*
* 弹出窗口代码
*/
function Func.isIe()
{
    return(document.all)?true:false;
}
//设置select的可见状态
function Func.setSelectState(state)
{
    var objl=document.getElementsByTagName("select");
    for(var i=0;i<objl.length;i++)
    {
    objl[i].style.visibility=state;
    }
}
function Func.GetcenterPosition(obj)
{
    return {x:(document.body.scrollLeft + (document.body.clientWidth-parseInt(obj.style.width))/2),y:(document.body.scrollTop + (document.body.clientHeight-parseInt(obj.style.height))/2)};
}

/// <summary>
/// 根据窗口客户端区域、滚动条位置、消息框宽高来计算显示位置
/// </summary>
function calcposition(backObj,msgObj)
{
    if (backObj.style.display != "none")
    {
        backObj.style.display = "none";
        msgObj.style.display = "none"
        setTimeout(function(){calcposition_timeout(backObj,msgObj);}, 0);
    }
}

function calcposition_timeout(backObj,msgObj)
{
    var bWidth = (document.body.scrollWidth > document.body.clientWidth) ? document.body.scrollWidth : document.body.clientWidth;
    var bHeight = (document.body.scrollHeight > document.body.clientHeight) ? document.body.scrollHeight : document.body.clientHeight;

    backObj.style.width = bWidth;
    backObj.style.height = bHeight;
    backObj.style.display = "";
    var pos = Func.GetcenterPosition(msgObj);
    msgObj.style.position = "absolute";
    msgObj.style.left = pos.x;
    msgObj.style.top = pos.y;
    msgObj.style.display = ""
}

//弹出方法
function Func.showMessageBox(windowid)
{
    if(Func.isIe){
        Func.setSelectState("hidden");}
    
    var back = $("MsgDiv_back");
    var mesW=$(windowid);
    if (!back)
    {
        back=document.createElement("div");
        back.id="MsgDiv_back";
        var styleStr="top:0px;left:0px;position:absolute;z-index:2;background:#666;";
            styleStr+=(Func.isIe)?"filter:alpha(opacity=10);":"opacity:0.40;";
        back.style.cssText=styleStr;
        document.body.insertBefore(back, document.body.firstChild);
        window.attachEvent("onresize", function(){calcposition(back,mesW);});
    }
    back.style.display = "";
    calcposition(back,mesW);
    back.filters.alpha.opacity = 10;
    Func.showBackground(back,40);
}


function Func.showBackground(obj,endInt)
{
    obj.filters.alpha.opacity+=1;
    if(obj.filters.alpha.opacity<endInt)
    {
        setTimeout(function(){Func.showBackground(obj,endInt)},10);
    }
}

//关闭窗口
function Func.closeWindow(windowid)
{
    $(windowid).style.display="none";
    if(Func.isIe){
        Func.setSelectState("");
    }
    $("MsgDiv_back").style.display = "none";
}